#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
地铁安检人流模拟主程序
用于模拟从地铁口到安检口再到E1口的人流时间和等待情况
"""

import json
import os
import glob
from datetime import datetime
from people_flow_generator import PeopleFlowGenerator
from security_simulation import SecuritySimulation


def save_results_to_file(results_v1, results_v2, output_file="simulation_results.txt"):
    """将模拟结果保存到文件"""
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("地铁安检模拟结果\n")
        f.write("=" * 50 + "\n\n")
        
        # 读取配置文件
        with open('config.json', 'r', encoding='utf-8') as config_file:
            config = json.load(config_file)
        
        # 打印第一版配置参数
        f.write("第一版模拟配置参数:\n")
        f.write("-" * 30 + "\n")
        
        # 地铁口配置
        f.write("地铁口配置:\n")
        for exit_name, exit_config in config["subway_exits"].items():
            f.write(f"  {exit_name}口: 人员比例={exit_config['ratio']:.1%}, 安检口类型={exit_config['security_gate']}, 到安检口距离={exit_config['distance_to_security']}米\n")
        
        # 安检口配置
        f.write("\n安检口配置:\n")
        f.write("  小安检口:\n")
        f.write(f"    每人安检时间: 15秒\n")
        f.write(f"    安检点数量: {config['security_gates']['small']['num_checkpoints']}个\n")
        f.write(f"    安检失败率: {config['security_gates']['small']['failure_rate']:.1%}\n")
        f.write(f"    重新安检等待时间: {config['security_gates']['small']['retry_time_minutes']}分钟\n")
        f.write(f"    到E1口距离: {config['security_gates']['small']['distance_to_E1']}米\n")
        
        f.write("  大安检口:\n")
        f.write(f"    每人安检时间: 15秒\n")
        f.write(f"    安检点数量: {config['security_gates']['large']['num_checkpoints']}个\n")
        f.write(f"    安检失败率: {config['security_gates']['large']['failure_rate']:.1%}\n")
        f.write(f"    重新安检等待时间: {config['security_gates']['large']['retry_time_minutes']}分钟\n")
        f.write(f"    到E1口距离: {config['security_gates']['large']['distance_to_E1']}米\n")
        
        # 其他配置
        f.write(f"\n其他配置:\n")
        f.write(f"  步行速度: {config['walking_speed']}米/秒\n")
        
        f.write(f"\n人流时间段配置:\n")
        for period in config["afternoon_periods"]:
            f.write(f"  {period['start_time']}-{period['end_time']}: {period['people_count']}人\n")
        
        # 打印第二版配置参数
        f.write("\n\n第二版模拟配置参数:\n")
        f.write("-" * 30 + "\n")
        
        # 地铁口配置
        f.write("地铁口配置:\n")
        for exit_name, exit_config in config["subway_exits"].items():
            f.write(f"  {exit_name}口: 人员比例={exit_config['ratio']:.1%}, 安检口类型={exit_config['security_gate']}, 到安检口距离={exit_config['distance_to_security']}米\n")
        
        # 安检口配置
        f.write("\n安检口配置:\n")
        f.write("  小安检口:\n")
        f.write(f"    每人安检时间: 30秒\n")
        f.write(f"    安检点数量: {config['security_gates']['small']['num_checkpoints']}个\n")
        f.write(f"    安检失败率: {config['security_gates']['small']['failure_rate']:.1%}\n")
        f.write(f"    重新安检等待时间: {config['security_gates']['small']['retry_time_minutes']}分钟\n")
        f.write(f"    到E1口距离: {config['security_gates']['small']['distance_to_E1']}米\n")
        
        f.write("  大安检口:\n")
        f.write(f"    每人安检时间: 30秒\n")
        f.write(f"    安检点数量: {config['security_gates']['large']['num_checkpoints']}个\n")
        f.write(f"    安检失败率: {config['security_gates']['large']['failure_rate']:.1%}\n")
        f.write(f"    重新安检等待时间: {config['security_gates']['large']['retry_time_minutes']}分钟\n")
        f.write(f"    到E1口距离: {config['security_gates']['large']['distance_to_E1']}米\n")
        
        # 其他配置
        f.write(f"\n其他配置:\n")
        f.write(f"  步行速度: {config['walking_speed']}米/秒\n")
        
        f.write(f"\n人流时间段配置:\n")
        for period in config["afternoon_periods"]:
            f.write(f"  {period['start_time']}-{period['end_time']}: {period['people_count']}人\n")
        
        f.write("\n\n")
        
        # 参数说明
        f.write("结果参数说明:\n")
        f.write("- 总人数: 参与模拟的总人数\n")
        f.write("- 平均总时长: 从到达地铁口到到达E1口的平均时间\n")
        f.write("- 最长总时长: 从到达地铁口到到达E1口的最长时间\n")
        f.write("- 最短总时长: 从到达地铁口到到达E1口的最短时间\n")
        f.write("- 平均等待时间: 从开始排队到通过安检的平均时间\n")
        f.write("- 最长等待时间: 从开始排队到通过安检的最长时间\n")
        f.write("- 安检不通过人数: 安检不通过需要重新安检的人数\n")
        f.write("- 所有人员完全到达E1口所需总时长: 从第一个人员到达地铁口到最后一个人员到达E1口的总时长\n\n")
        
        f.write("第一版：小安检口15秒/人(总处理能力=0.67人/秒)，大安检口15秒/人(总处理能力=1.33人/秒)\n")
        f.write("-" * 30 + "\n")
        f.write(f"总人数: {results_v1['total_people']}人\n")
        f.write(f"平均总时长: {results_v1['avg_total_time']:.2f}分钟\n")
        f.write(f"最长总时长: {results_v1['max_total_time']:.2f}分钟\n")
        f.write(f"最短总时长: {results_v1['min_total_time']:.2f}分钟\n")
        f.write(f"平均等待时间: {results_v1['avg_wait_time']:.2f}分钟\n")
        f.write(f"最长等待时间: {results_v1['max_wait_time']:.2f}分钟\n")
        f.write(f"安检不通过人数: {results_v1['failed_people']}人\n")
        f.write(f"所有人员完全到达E1口所需总时长: {results_v1['all_people_arrival_time']:.2f}分钟\n\n")
        
        f.write("第二版：小安检口30秒/人(总处理能力=0.33人/秒)，大安检口30秒/人(总处理能力=0.67人/秒)\n")
        f.write("-" * 30 + "\n")
        f.write(f"总人数: {results_v2['total_people']}人\n")
        f.write(f"平均总时长: {results_v2['avg_total_time']:.2f}分钟\n")
        f.write(f"最长总时长: {results_v2['max_total_time']:.2f}分钟\n")
        f.write(f"最短总时长: {results_v2['min_total_time']:.2f}分钟\n")
        f.write(f"平均等待时间: {results_v2['avg_wait_time']:.2f}分钟\n")
        f.write(f"最长等待时间: {results_v2['max_wait_time']:.2f}分钟\n")
        f.write(f"安检不通过人数: {results_v2['failed_people']}人\n")
        f.write(f"所有人员完全到达E1口所需总时长: {results_v2['all_people_arrival_time']:.2f}分钟\n")


def run_simulation_with_security_speed(small_seconds, large_seconds):
    """运行指定安检速度的模拟"""
    # 读取配置文件
    with open('config.json', 'r', encoding='utf-8') as f:
        config = json.load(f)
    
    # 修改安检速度配置
    config["security_gates"]["small"]["seconds_per_person"] = small_seconds
    config["security_gates"]["large"]["seconds_per_person"] = large_seconds
    
    # 保存修改后的配置
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=2)
    
    # 生成人流
    flow_generator = PeopleFlowGenerator('config.json')
    afternoon_people = flow_generator.generate_afternoon_flow()
    
    # 模拟安检过程
    security_sim = SecuritySimulation('config.json')
    security_sim.simulate(afternoon_people, 'afternoon')
    
    # 返回结果
    return security_sim.get_results('afternoon')


def main():
    """主函数"""
    # 删除旧的结果文件
    for file in glob.glob("simulation_results_*.txt"):
        os.remove(file)
    
    # 运行第一版模拟：小安检口15秒/人，大安检口15秒/人
    print("运行第一版模拟：小安检口15秒/人(总处理能力=0.67人/秒)，大安检口15秒/人(总处理能力=1.33人/秒)...")
    results_v1 = run_simulation_with_security_speed(15, 15)
    
    # 运行第二版模拟：小安检口30秒/人，大安检口30秒/人
    print("运行第二版模拟：小安检口30秒/人(总处理能力=0.33人/秒)，大安检口30秒/人(总处理能力=0.67人/秒)...")
    results_v2 = run_simulation_with_security_speed(30, 30)
    
    # 保存结果
    save_results_to_file(results_v1, results_v2)
    
    print("模拟完成，结果已保存到 simulation_results.txt 文件")


if __name__ == "__main__":
    main()